package com.operator.Activitys.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.operator.Activitys.R;
import com.operator.Activitys.activity.base.BaseActivity;
import com.operator.Activitys.bean.MoneyState;
import com.operator.Activitys.bean.SearchShop;
import com.operator.Activitys.bean.State;
import com.operator.Activitys.bean.User;
import com.operator.Activitys.dialog.PopEnterPassword;
import com.operator.Activitys.http.manager.UserManager;
import com.operator.Activitys.utils.Constant;
import com.operator.Activitys.utils.FrescoUtils;
import com.operator.Activitys.utils.JumperUtils;
import com.operator.Activitys.utils.ToastUtils;
import com.operator.Activitys.utils.UiUtil;
import com.zhy.autolayout.AutoRelativeLayout;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 项目名称：金泽云 手机app
 * 类描述：转账
 * 创建人：张飞祥
 * 创建时间：2018/5/23 17:33
 * 修改人：张飞祥
 * 修改时间：2018/5/23 17:33
 * 修改备注：
 */
public class TransferActivity extends BaseActivity  implements TextWatcher {

    //返回按钮
    @Bind(R.id.iv_return)
    ImageView ivReturn;
    //标题
    @Bind(R.id.tv_title)
    TextView tvTitle;
    //功能键
    @Bind(R.id.tv_function)
    TextView tvFunction;
    //标题总布局
    @Bind(R.id.app_bar_layout)
    AutoRelativeLayout appBarLayout;
    //转账店铺头像
    @Bind(R.id.sv_transfer_icon)
    SimpleDraweeView svTransferIcon;
    //转账店铺名称
    @Bind(R.id.tv_transfer_name)
    TextView tvTransferName;
    //转账金额
    @Bind(R.id.et_transfer_number)
    EditText etTransferNumber;
    //当前余额
    @Bind(R.id.tv_transfer_money)
    TextView tvTransferMoney;
    @Bind(R.id.btn_transfer)
    Button btnTransfer;

    //转账金额
    private double mPutForwardMoney;
    //初始化网络请求
    public UserManager mApiManager;
    //TODO 当前 内存中 用户信息
    private User mACacheUser = null;
    //转账输入金额
    private double mAmount = 0;
    //现有金额
    private double mRemainder = 0;

    //向谁转账的 店铺实体
    private  SearchShop mToShop = null ;

    //支付 弹窗
    private PopEnterPassword mPopPayPwd = null;

    @Override
    protected void initUI() {
        setContentView(R.layout.act_transfer);

        //网络请求接口 常驻方法
        mApiManager = mApiManager.getUserApiManager(this,this.getTaskId());
        //TODO 获取内存用户实体
        Gson gson = new Gson();
        mACacheUser = gson.fromJson(mACache.getAsJSONObject(Constant.CACHE_USER) + "", User.class);

        //TODO  获取从上个页面传递过来的实体数据
        Bundle bundle = this.getIntent().getExtras();
        //非空判断
        if (bundle!=null){
            //获取 实体数据
            mToShop = (SearchShop) bundle.getSerializable(Constant.INTENT_SEARCH_SHOP_BEAN);
            //店铺头像
            FrescoUtils.loadImage(mToShop.getImgUrl(),svTransferIcon);
            //店铺名称
            tvTransferName.setText(mToShop.getStoreName());
        }

        //设置标题
        tvTitle.setText("转账");
        //显示返回按钮
        ivReturn.setVisibility(View.VISIBLE);
        //显示功能按钮
        tvFunction.setVisibility(View.VISIBLE);
        //显示功能按钮 文字
        tvFunction.setText("转账记录");
        //设置状态栏 背景颜色
        appBarLayout.setBackgroundResource(R.color.color_bg_blue);
    }

    @Override
    protected void initData() {
        //转账其他数量 文字输入监听 事件
        etTransferNumber.addTextChangedListener(this);
        //显示金额
        tvTransferMoney.setText("当前余额："+mACacheUser.getRemainder()+"元");
    }

    /**
     * 金额其他数量监听事件
     */
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }
    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        //TODO 获取内存 最新的 用户实体
        User user = new Gson().fromJson(mACache.getAsJSONObject(Constant.CACHE_USER) + "", User.class);

        //TODO 判断当前 显示的具体价格
        if (charSequence.toString().equals(".")) {
            //清空数据源
            etTransferNumber.setText("");
        }else if (!charSequence.toString().equals("")){
            //设置现有金额
            mRemainder =user.getRemainder();
            //提现数量
            mAmount = Double.parseDouble(charSequence.toString());
            //逻辑判断
            if (mAmount > mRemainder) {
                etTransferNumber.setText(mRemainder + "");
                //设置 提现金额
                mPutForwardMoney = mRemainder;
                return;
            } else {
                //设置 提现金额
                mPutForwardMoney = mAmount;
            }
        }else {
            //初始化 提现金额
            mPutForwardMoney = 0;
        }
    }
    @Override
    public void afterTextChanged(Editable editable) {
    }

    /**
     * 按钮点击事件
     */
    @OnClick({R.id.iv_return,R.id.tv_function,R.id.btn_transfer})
    public void onBtnClick(View v) {
        switch (v.getId()) {

            case R.id.iv_return:            //返回
                finish();
                break;

            case R.id.tv_function:          //转账记录
                JumperUtils.JumpTo(this,TransferListActivity.class);
                break;

            case R.id.btn_transfer:         //转账

                //TODO 隐藏其他数量 软件盘
                UiUtil.hideKeyboard(etTransferNumber, TransferActivity.this);
                //TODO 开始业务逻辑判断
                if (mPutForwardMoney == 0){
                    ToastUtils.showShort(TransferActivity.this,"请输入转账金额！");
                }else{
                    /**
                     * 重新 获取用户实体对象，判断 支付密钥是否为空
                     * true： 跳转 设置 支付密码
                     * false：则直接 开启支付
                     */
                    mACacheUser = new Gson().fromJson(mACache.getAsJSONObject(Constant.CACHE_USER) + "", User.class);
                    if (mACacheUser.getTsPwd() != null  && !mACacheUser.getTsPwd().equals("")){
                        //弹出支付软件盘
                        setShowPayPopupView("向"+mToShop.getStoreName()+"转账", mPutForwardMoney);
                    }else{
                        JumperUtils.JumpTo(this,PayManageActivity.class);
                    }
                }
                break;
        }
    }

    /**
     * 显示 支付视图弹窗
     */
    private void setShowPayPopupView(String title, double money) {

        //TODO 配置弹窗
        mPopPayPwd = new PopEnterPassword(TransferActivity.this, title, money) {
            //输入支付密码完成后，所要进行的操作
            @Override
            public void setOnFinishInput(String pwd) {
                //弹出加载框
                initShowTimeDialog("正在验证支付密钥....", TransferActivity.this);
                //开始验证支付密码
                mApiManager.userCheckPayPwd(mACacheUser.getId(), pwd);
            }
        };

        /**
         * 显示 支付窗口
         * ps：设置 “Gravity” layout在PopupWindow中显示的位置
         */
        mPopPayPwd.showAtLocation(TransferActivity.this.findViewById(R.id.layout_transfer),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 验证支付 报错
     */
    @Subscriber(tag = Constant.BUS_MY_CHECK_PAY_ERROR, mode = ThreadMode.MAIN)
    public void initCheckPayError(String strError) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //销毁加载提示框
                timeDialog.dismiss();
                //弹出提示
                ToastUtils.showShort(TransferActivity.this, "转账失败，网络连接不稳定！");
            }
        }, 2000);
    }

    /**
     * 验证支付
     */
    @Subscriber(tag = Constant.BUS_MY_CHECK_PAY, mode = ThreadMode.MAIN)
    public void initCheckPay(final State state) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //TODO 判断当前是否验证成功
                if (state.getState().equals("1")) {
                    //设置 提示信息
                    timeDialog.setContent("正在转账，请稍候...");
                    //开始 转账 网络请求
                    mApiManager.userTransfer(mACacheUser.getStoreName(),mToShop.getStoreName(),mPutForwardMoney);
                } else {
                    //销毁加载提示框
                    timeDialog.dismiss();
                    //显示提示信息 dialog
                    new MaterialDialog.Builder(TransferActivity.this)
                            .content("支付密码错误，请重试")
                            .negativeText("重试")
                            .negativeColor(Color.parseColor("#cccccc"))
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    //弹出支付软件盘
                                    setShowPayPopupView("向"+mToShop.getStoreName()+"转账", mPutForwardMoney);
                                }
                            })
                            .positiveText("忘记密码")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    //跳转忘记 支付密码页面
                                    JumperUtils.JumpTo(TransferActivity.this, PayForgetPwdActivity.class);
                                }
                            }).show();
                }
            }
        }, 2000);
    }

    /**
     * 极光推送 更新余额信息
     * @param JPushMoney
     */
    @Subscriber(tag = Constant.BUS_MY_REMAINDER)
    public void onJpushShopMoneyPush(double JPushMoney) {
        //TODO 更新 余额信息
        tvTransferMoney.setText("当前余额："+JPushMoney+"元");
        //TODO 更新 页面上的 店铺实体
        mACacheUser.setRemainder(JPushMoney);
    }

    /**
     * 转账 报错
     */
    @Subscriber(tag = Constant.BUS_MY_TRANSFER_ERROR, mode = ThreadMode.MAIN)
    public void initTransferError(String httpTransferError) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //隐藏加载
                timeDialog.dismiss();
                //弹出提示
                ToastUtils.showShort(TransferActivity.this,"转账失败，网络连接不稳定！");
            }
        }, 1000);
    }

    /**
     * 转账 返回数据
     */
    @Subscriber(tag = Constant.BUS_MY_TRANSFER, mode = ThreadMode.MAIN)
    public void initTransfer(final MoneyState state) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //隐藏加载
                timeDialog.dismiss();
                //TODO 业务逻辑判断
                if ("1".equals(state.getState())){

                    //保存新的 用户余额参数
                    mACacheUser.setRemainder(state.getCurentRemainder());
                    mACache.put(Constant.CACHE_USER, new Gson().toJson(mACacheUser));
                    //清空输入文本
                    etTransferNumber.setText("");
                    //更新显示金额
                    tvTransferMoney.setText("当前余额："+state.getCurentRemainder()+"元");
                    //更新我的页面 余额
                    EventBus.getDefault().post(state.getCurentRemainder(),Constant.BUS_MY_REMAINDER);
                }
                //弹出提示
                ToastUtils.showShort(TransferActivity.this,state.getMsg());
            }
        }, 1000);
    }

}
